<template>
  <div class="login-page">
    <div class="header">
      <div class="logo">
        <span>VICHI.</span>
      </div>
      <div class="tagline">
        <span>向内探索，向上生长——薇启伴你觉醒潜能</span>
      </div>
      <div class="home-link">
        <router-link to="/home">
          <el-button
            size="large"
            round
            style="background-color: black; width: 100px; color: white"
          >
            首 页
          </el-button>
        </router-link>
      </div>
    </div>

    <div class="login-container">
      <div class="login-image">
        <img src="/src/assets/img1.png" alt="Login Image" />
      </div>
      <div class="login-form-container">
        <el-form
          ref="loginRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
        >
          <img
            src="/src/assets/font.png"
            alt="Logo"
            style="height: 20px; margin-bottom: 15px"
          />

          <el-form-item prop="username">
            <span>用户名：</span>
            <el-input
              v-model="loginForm.username"
              size="large"
              auto-complete="off"
              placeholder="用户名"
              style="width: 280px; margin-left: 5px"
            >
              <template #prefix>
                <svg-icon icon="user" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <span>密码：</span>
            <el-input
              v-model="loginForm.password"
              type="password"
              size="large"
              auto-complete="off"
              placeholder="密码"
              style="width: 280px; margin-left: 18px"
              @keyup.enter="debouncedHandleLogin"
            >
              <template #prefix>
                <svg-icon icon="password" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <div class="remember-and-links">
              <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
              <el-link
                type="info"
                @click="handleForgetPasswordClick"
                class="forget-password-link"
              >
                忘记密码？
              </el-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              size="large"
              style="width: 100%; background-color: black"
              @click.prevent="debouncedHandleLogin"
            >
              <span style="color: white">登 录</span>
            </el-button>
          </el-form-item>

          <div class="register-link-container">
            <el-link
              type="info"
              @click="handleRegisterClick"
              class="register-link"
            >
              没有账号？点击注册
            </el-link>
          </div>
        </el-form>
      </div>
    </div>

    <div class="footer">
      <div class="copyright">
        <span>Copyright © 2025 薇启Vichi 版权所有</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import requestUtil from "@/util/request";
import { useMainStore } from "@/stores/index";
import qs from "qs";
import { ElMessage } from "element-plus";
import router from "@/router";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/util/jsencrypt";
import { debounce } from "@/util/debounce";

// Coze API 配置
const COZE_API_URL = "https://api.coze.cn/v1/variables";

const COZE_BOTS = [
  {
    name: "心聆秘语智能体",
    botId: "7517556753664622607",
    connectorId: "1024",
    apiKey:
      "pat_NOrsA24YEKmGN6peXeP1rT37hUFyvaEuaM18QYsHZzwFpUkkXSUV4G7P3440i7Cj",
  },
  {
    name: "睿记精解智能体",
    botId: "7514970706363842614",
    connectorId: "1024",
    apiKey:
      "pat_nh9LMJQm7QIL62DG5YswZdt5INdKYkEev3ENcRDow5QXhcAG70Q8DSxQlN1wK9rr",
  },
];

const loginRef = ref(null);

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
});

const loginRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const store = useMainStore();

// 为单个智能体设置 Coze 用户变量
const setCozeUserVariablesForBot = async (userInfo, botConfig) => {
  try {
    console.log(`开始为${botConfig.name}设置 Coze 用户变量:`, userInfo);

    const requestBody = {
      bot_id: botConfig.botId,
      connector_id: botConfig.connectorId,
      connector_uid: userInfo.id.toString(),
      data: [
        {
          keyword: "user_id",
          value: userInfo.id.toString(),
        },
        {
          keyword: "user_name",
          value: userInfo.username || "未知用户",
        },
        {
          keyword: "email",
          value: userInfo.email || "",
        },
      ],
    };

    console.log(
      `发送到 ${botConfig.name} 的请求体:`,
      JSON.stringify(requestBody, null, 2)
    );

    const response = await fetch(COZE_API_URL, {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${botConfig.apiKey}`, // 使用每个智能体独立的API_KEY
        "Content-Type": "application/json",
      },
      body: JSON.stringify(requestBody),
    });

    if (response.ok) {
      const result = await response.json();
      console.log(`${botConfig.name} 用户变量设置成功:`, result);
      return { success: true, botName: botConfig.name };
    } else {
      const errorText = await response.text();
      console.error(`${botConfig.name} 用户变量设置失败:`, {
        status: response.status,
        statusText: response.statusText,
        body: errorText,
      });
      return { success: false, botName: botConfig.name, error: errorText };
    }
  } catch (error) {
    console.error(`设置 ${botConfig.name} 用户变量时发生错误:`, error);
    return { success: false, botName: botConfig.name, error: error.message };
  }
};

// 为所有智能体设置 Coze 用户变量
const setCozeUserVariables = async (userInfo) => {
  console.log("开始为所有智能体设置 Coze 用户变量:", userInfo);

  const results = [];

  // 并行处理所有智能体
  const promises = COZE_BOTS.map((botConfig) =>
    setCozeUserVariablesForBot(userInfo, botConfig)
  );

  try {
    const allResults = await Promise.allSettled(promises);

    allResults.forEach((result, index) => {
      if (result.status === "fulfilled") {
        results.push(result.value);
        if (result.value.success) {
          console.log(`✅ ${result.value.botName} 用户变量设置成功`);
        } else {
          console.warn(
            `⚠️ ${result.value.botName} 用户变量设置失败:`,
            result.value.error
          );
        }
      } else {
        const botName = COZE_BOTS[index].name;
        console.error(`❌ ${botName} 用户变量设置异常:`, result.reason);
        results.push({ success: false, botName, error: result.reason });
      }
    });

    // 统计结果
    const successCount = results.filter((r) => r.success).length;
    const totalCount = COZE_BOTS.length;

    console.log(
      `Coze 用户变量设置完成: ${successCount}/${totalCount} 个智能体设置成功`
    );

    // 如果至少有一个成功，就认为是成功的
    return successCount > 0;
  } catch (error) {
    console.error("设置 Coze 用户变量时发生未预期的错误:", error);
    return false;
  }
};

// 登录处理函数
const handleLogin = async () => {
  loginRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 对密码进行加密
        const encryptedPassword = encrypt(loginForm.value.password);

        // 构建提交的数据对象
        const loginData = {
          username: loginForm.value.username,
          password: encryptedPassword,
          rememberMe: loginForm.value.rememberMe,
        };

        // 发送登录请求
        let result = await requestUtil.post("/login", qs.stringify(loginData));
        let data = result.data;

        if (data.code === 200) {
          // 处理记住密码逻辑
          if (loginForm.value.rememberMe) {
            Cookies.set("username", loginForm.value.username, { expires: 30 });
            Cookies.set("password", encryptedPassword, { expires: 30 });
            Cookies.set("rememberMe", loginForm.value.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }

          const token = data.authorization;
          const menuList = data.menuList;
          const currentUser = data.currentUser;
          const roleIds = data.roleIds || [];

          // 更新 store中的数据
          store.SET_MENULIST(menuList);
          store.SET_TOKEN(token);
          store.SET_USERINFO({ ...currentUser, roleIds });

          // 设置 Coze 用户变量（为所有智能体）
          try {
            const cozeResult = await setCozeUserVariables(currentUser);
            if (cozeResult) {
              console.log("✅ 所有智能体的 Coze 用户变量设置完成");
            } else {
              console.warn(
                "⚠️ 部分或全部智能体的 Coze 用户变量设置失败，但不影响登录流程"
              );
            }
          } catch (error) {
            console.warn("❌ 设置用户变量异常，但不影响登录流程:", error);
          }

          // 跳转到首页
          router.replace({ name: "首页" });
        } else {
          ElMessage.error(data.msg);
        }
      } catch (error) {
        console.error("登录请求失败:", error);
      }
    }
  });
};

// 使用防抖函数包装 handleLogin
const debouncedHandleLogin = debounce(handleLogin, 500);

// 获取Cookie中的用户信息并填充表单
function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");

  loginForm.value = {
    username: username || loginForm.value.username,
    password: password ? decrypt(password) : loginForm.value.password,
    rememberMe: rememberMe ? Boolean(rememberMe) : false,
  };
}

onMounted(() => {
  getCookie();
});

// 处理注册链接点击事件的方法
const handleRegisterClick = () => {
  router.push("/register");
};

// 处理忘记密码链接点击事件的方法
const handleForgetPasswordClick = () => {
  router.push("/resetpassword");
};
</script>

<style lang="scss" scoped>
.login-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f6f6f6;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  padding: 20px;
  margin-bottom: 20px;
}

.logo {
  margin-left: 10px;
  font-size: 50px;
  font-weight: bold;
  color: black;
}

.tagline {
  flex-grow: 1;
  margin-left: 20px;
  font-size: 20px;
  font-weight: bold;
  color: black;
  white-space: nowrap;
}

.home-link {
  margin-left: auto;
  margin-right: 20px;
}

.login-container {
  display: flex;
  flex-grow: 1;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
}

.login-image {
  width: 40%;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    max-width: 100%;
    height: auto;
  }
}

.login-form-container {
  width: 40%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-form {
  border-radius: 10px;
  background: #ffffff;
  width: 350px;
  padding: 35px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);

  .features {
    display: flex;
    justify-content: center;
    gap: 40px;
    margin-bottom: 15px;
  }

  .feature-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    color: #555;
  }

  .feature-item img {
    width: 40px;
    height: 40px;
  }

  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
}

.remember-and-links {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.register-link-container {
  text-align: center;
  margin-top: 20px;
}

.register-link,
.forget-password-link {
  text-decoration: none;
  color: #010101;
  font-size: 14px;

  &:hover {
    cursor: pointer;
  }
}

.footer {
  width: 100%;
  background-color: white;
  text-align: center;
  padding: 20px;
  margin-top: auto;
}

.copyright {
  font-size: 12px;
  color: #888;
}

// 响应式布局
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .tagline {
    margin: 10px 0;
  }

  .home-link {
    margin: 10px 0;
  }

  .login-container {
    flex-direction: column;
  }

  .login-image,
  .login-form-container {
    width: 100%;
    margin-bottom: 20px;
  }
}
</style>
